package server;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;

import common.IAuctionListener;
import common.IAuctionServer;
import common.Item;

public class AuctionServer implements IAuctionServer {

	private static AuctionServer instance = new AuctionServer();
	private ArrayList<Item> items;
	private HashMap<String, ArrayList<IAuctionListener>> itemListeners = new HashMap<String, ArrayList<IAuctionListener>>();
	
	private AuctionServer() {
		items = new ArrayList<Item>();
	}
	
	public static AuctionServer instance() {
		return instance;
	}
	
	@Override
	public void placeItemForBid(String ownerName, String itemName,
			String itemDesc, double startBid, int auctionTime)
			throws RemoteException {
		
		for (Item item : items) {
			if (item.getName().equals(itemName)) {
				throw new RemoteException("Item with this name already exists on auction server!");
			}
		}
		
		Item newItem = new Item(itemName, itemDesc, ownerName, "", startBid, auctionTime);
		items.add(newItem);
		
		Timer auctionTimer = new Timer();
		auctionTimer.schedule(new AuctionTimerTask(newItem, items, this), 0, 1000);
		
		
		System.out.println("New item added!");
	}

	@Override
	public void bidOnItem(String bidderName, String itemName, double bid)
			throws RemoteException {
		for( Item i : items){
			if(i.getName().equals(itemName) && i.getCurrentBid() < bid){
				i.setCurrentBid(bid);
				i.setCurrentBidder(bidderName);
				notifyListeners(i);
			}
		}		
	}

	@Override
	public List<Item> getItems() throws RemoteException {
		return this.items;
	}

	@Override
	public void registerListener(IAuctionListener al, String itemName)
			throws RemoteException {
		ArrayList<IAuctionListener> auctionListeners = itemListeners.get(itemName);
		
		if (auctionListeners == null) {
			auctionListeners = new ArrayList<IAuctionListener>();
		}
		
		auctionListeners.add(al);
		itemListeners.put(itemName, auctionListeners);
	
	}
	
	public void notifyListeners(Item item) {
		
		ArrayList<IAuctionListener> listeners = itemListeners.get(item.getName());
		
		for (IAuctionListener listener : listeners) {
			
			try {
				listener.update(item);
			}
			catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}

}
